//
//  USMemorialDayController.m
//  us
//
//  Created by karry on 2025/4/23.
//

#import "USMemorialDayController.h"
#import "USMainHeaderView.h"
#import "USMemorialDayCell.h"
#import "USAddMemorialDayController.h"
#import "USMemorialChangeStickerCell.h"
#import "USMemorialDayModel.h"
#import "USMemorialDayDetailVC.h"
#import "USMemorialHeaderView.h"
@interface USMemorialDayController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property (nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic,strong) NSMutableArray <USMemorialDayModel *>*daysList;

@property (nonatomic,strong) USMemorialDayModel *homePageDayModel;

@end

@implementation USMemorialDayController


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.prefersLargeTitles = YES;
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"纪念日";
    
    self.navigationController.navigationBar.prefersLargeTitles = YES;
    
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAutomatic;
    
    self.navigationController.navigationBar.largeTitleTextAttributes = @{
        NSFontAttributeName: [UIFont boldSystemFontOfSize:32],
        NSForegroundColorAttributeName: [UIColor labelColor]
    };

    [self setupView];
}

- (void)loadData{
    [super loadData];
    
    [[EMNetWork shareManager] em_post:API_AnniversaryList
                               params:@{@"sharedSpaceId":USUser.user.sharedSpaceId?:@""}
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            [self loadingFailed];
            return;
        }

        USMemorialDaySuperModel *superModel = [USMemorialDaySuperModel mj_objectWithKeyValues:api.data];
        self.homePageDayModel = superModel.homePageAnniversary;
        [self.daysList removeAllObjects];
        
        [self.daysList addObjectsFromArray:superModel.noRepeatYearlylist];
        [self.daysList addObjectsFromArray:superModel.repeatYearlylist];
        if (superModel.noRepeatYearlylist.count == 0 && superModel.repeatYearlylist.count == 0) {
            self.dataState = EmptyDataStateNoData;
        }
        
        [self.collectionView reloadData];
        [self.collectionView reloadEmptyDataSet];
        
        
        // Sync to widget
        NSMutableArray *allModels = [NSMutableArray array];
        [allModels addObjectsFromArray:superModel.noRepeatYearlylist];
        [allModels addObjectsFromArray:superModel.repeatYearlylist];
        [self syncMemorialDaysToWidgetWithList:allModels];
        
        
    } fail:^{
        
        
    }];

}

#pragma mark - Widget Sync

- (void)syncMemorialDaysToWidgetWithList:(NSArray<USMemorialDayModel *> *)list {
    NSMutableArray *dictArray = [NSMutableArray array];
    for (USMemorialDayModel *model in list) {
        [dictArray addObject:[model mj_keyValues]];
    }

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictArray options:0 error:nil];
    NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.emmo.us"];
    [defaults setObject:jsonData forKey:@"memorialDayList"];
    [defaults synchronize];
}


- (void)setupView{
    
    CGFloat margin = 16;
    
    CGFloat itemW = (self.view.bounds.size.width - margin * 3)/2.f;
    CGFloat itemH = itemW * 178/174;

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(itemW, itemH);
    layout.minimumLineSpacing = margin;
    layout.sectionInset = UIEdgeInsetsMake(margin, margin, margin, margin);
    layout.headerReferenceSize = CGSizeMake(0, 190);
    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    self.collectionView.backgroundColor = UIColor.clearColor;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.emptyDataSetSource = self;
    self.collectionView.emptyDataSetDelegate = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"USMemorialDayCell" bundle:nil] forCellWithReuseIdentifier:@"USMemorialDayCellId"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"USMemorialHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"USMemorialHeaderViewId"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"EmptySupplementaryView"];
    [self.view addSubview:self.collectionView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_add"] style:UIBarButtonItemStylePlain target:self action:@selector(addAction:)];

}

- (NSMutableArray <USMemorialDayModel *>*)daysList {
    if (_daysList == nil) {
        _daysList = [NSMutableArray array];
    }
    return _daysList;
}

#pragma mark - action
- (void)addAction:(id)sender{
    [USFeedbackTool impactSoft];
 
    USAddMemorialDayController *vc = [USAddMemorialDayController new];
    [self.navigationController pushViewController:vc animated:YES];
    
}


#pragma mark - <UICollectionViewDelegate,UICollectionViewDataSource>

 
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.daysList.count;
    
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    USMemorialDayCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"USMemorialDayCellId" forIndexPath:indexPath];
    
    USMemorialDayModel *dayModel = self.daysList[indexPath.item];
   
    cell.dayView.dayModel = dayModel;
    return cell;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    USMemorialDayDetailVC *vc = [[USMemorialDayDetailVC alloc]init];
    USMemorialDayModel *dayModel = self.daysList[indexPath.item];
    if ([dayModel.anniversaryId isEqualToString: self.homePageDayModel.anniversaryId]) {
        dayModel.homePageFlag = 1;
    }else{
        dayModel.homePageFlag = 0;
    }
  
    vc.dayModel = dayModel;
    [self.navigationController pushViewController:vc animated:YES];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == 0 && self.homePageDayModel) {
        return CGSizeMake(0, 190);
    } else {
        return CGSizeZero;
    }
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader && indexPath.section == 0 && self.homePageDayModel) {
 
        USMemorialHeaderView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"USMemorialHeaderViewId" forIndexPath:indexPath];

        headView.leftCharacterView.character = USUser.user.character;
        headView.rightCharacterView.character = USUser.user.relCharacter;

        UIColor *color = [UIColor jk_colorWithHexString:self.homePageDayModel.color];
        headView.topView.backgroundColor = [color colorWithAlphaComponent:0.5];
        headView.titleLab.text = self.homePageDayModel.anniversaryName;
        headView.titleLab.textColor = [color jk_darkenColor:0.35];
        headView.dayLab.text = self.homePageDayModel.dayDescription;

        headView.contentLab.attributedText = [self.homePageDayModel dayAttributeWithFontSize:28];
 
 
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] init];
        [headView addGestureRecognizer:tapGesture];
 
        @weakify(self)
        [[tapGesture rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            @strongify(self)
            USMemorialDayDetailVC *vc = [[USMemorialDayDetailVC alloc]init];
            vc.dayModel = self.homePageDayModel;
            [self.navigationController pushViewController:vc animated:YES];
        }];
         
        return headView;
    }
    return [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"EmptySupplementaryView" forIndexPath:indexPath];
}



#pragma mark - DZNEmptyDataSetSource,DZNEmptyDataSetDelegate


- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView{
    
    if (self.dataState == EmptyDataStateLoading) {
        UIView *contentView = [UIView new];
        contentView.frame = CGRectMake(0, 0, self.view.jk_width, 200);
        
        NSString *gifPath = [[NSBundle mainBundle] pathForResource:@"load_page" ofType:@"gif"];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:nil];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.frame = CGRectMake(0, 0, 200, 200);
        [imageView sd_setImageWithURL:[NSURL fileURLWithPath:gifPath]];
        
        [contentView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(200);
            make.center.mas_equalTo(contentView);
        }];
        
        return contentView;
    }
    
    USEmptyView *emptyView = [[USEmptyView alloc] initWithFrame:CGRectMake(0, 0, self.view.jk_width, 0)];
    emptyView.image = [UIImage imageNamed:@"memorialDay_Empty"];
    emptyView.title = @"应该不会有这个情况反正先搞了";
    emptyView.btnTitle = @"添加纪念日";
    emptyView.userInteractionEnabled = YES;
    [emptyView.btn addTarget:self action:@selector(addAction:) forControlEvents:UIControlEventTouchUpInside];
    return emptyView;
    
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    
    
    return YES; // 允许点击
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    
    
    return YES; // 避免 scrollView 吃掉 touch 事件
}

@end
